package com.taichuan.selfcheck.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.config.PropertyDefaultValue;
import com.taichuan.selfcheck.eventbus.QrcodeEvent;
import com.taichuan.selfcheck.mvp.presenter.EmptyPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.EmptyInterface;
import com.taichuan.selfcheck.ui.dialog.ResultDialog;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.serialcommunication.SerialPortPublic;
import com.taichuan.tcutils.HexUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 二维码测试页面
 *
 * @author lqd
 */
public class QrcodeTestFragment extends AppBaseFragment<EmptyInterface, EmptyPresenter> implements EmptyInterface {

    private static final String TAG = "QrcodeTestFragment";

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    protected EmptyPresenter createPresenter() {
        return new EmptyPresenter();
    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_qrcode_test;
    }

    ResultDialog resultDialog;

    @BindView(R.id.passThroughDataTv)
    TextView passThroughDataTv;
    @BindView(R.id.controlQrcodeResStatusBtn)
    Button controlQrcodeResStatusBtn;
    @BindView(R.id.controlQrcodeTrigStatusBtn)
    Button controlQrcodeTrigStatusBtn;

    @Override
    protected void initView(View view, Bundle bundle) {
        EventBus.getDefault().register(this);
        //设置弹窗发送的事件——二维码测试
        resultDialog = new ResultDialog(PropertyDefaultValue.FUNCTION_TEST_17, getResources().getString(R.string.qrcode_test), getContext());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({
            R.id.controlQrcodeResStatusBtn,
            R.id.controlQrcodeTrigStatusBtn
    })
    @Override
    protected void onXmlClick(View v) {
        super.onXmlClick(v);
        final int id = v.getId();
        if (id == R.id.controlQrcodeResStatusBtn) {
            resetQrcode();
        } else if (id == R.id.controlQrcodeTrigStatusBtn) {
            triggerQrcode();
        }
    }

    @Override
    public void doOnAutoFinishFragment() {
        resultDialog.show();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (resultDialog.isShowing()) {
            resultDialog.dispatchKeyEvent(event);
        }
        if (event.getKeyCode() == KeyEvent.KEYCODE_1) {
            controlQrcodeResStatusBtn.performClick();
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_2) {
            controlQrcodeTrigStatusBtn.performClick();
        }
        return super.dispatchKeyEvent(event);
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrcodeEvent(QrcodeEvent event) {
        byte[] data = event.data;
        try {
            passThroughDataTv.setText("透传数据：" + HexUtils.getFormatHex(data)
                    + "\n透传数据(UTF-8)：" + new String(data, StandardCharsets.UTF_8)
                    + "\n透传数据(ISO_8859_1)：" + new String(data, StandardCharsets.ISO_8859_1)
                    + "\n透传数据(GB2312)：" + new String(data, "GB2312")
            );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static final ExecutorService threadPool = Executors.newCachedThreadPool();

    private Future<Object> resetQrcodeFuture;

    /**
     * 重置二维码
     */
    public void resetQrcode() {
        if (resetQrcodeFuture != null) {
            Log.w(TAG, "resetQrcode: 不要频繁触发");
            return;
        }
        resetQrcodeFuture = threadPool.submit(() -> {
            try {
                // 首先拉低Res脚电平
                SerialPortPublic.controlQrcodeResStatus(0, -1);
                // 等待一会
                Thread.sleep(100);
                // 然后拉高Res脚电平
                SerialPortPublic.controlQrcodeResStatus(1, -1);
                return null;
            } finally {
                resetQrcodeFuture = null;
            }
        });
    }

    private Future<Object> triggerQrcodeFuture = null;

    /**
     * 出发二维码扫描动作
     * <p>
     * 二维码硬件模块默认自动扫描（在摄像头前有物体移动自动进行扫描操作），这个方法用于在程序中主动触发扫描动作。
     */
    public void triggerQrcode() {
        if (triggerQrcodeFuture != null) {
            Log.w(TAG, "triggerQrcode: 不要频繁触发");
            return;
        }
        triggerQrcodeFuture = threadPool.submit(() -> {
            try {
                // 首先拉高Trig脚电平
                SerialPortPublic.controlQrcodeTrigStatus(1, -1);
                // 等待一会
                Thread.sleep(100);
                // 然后拉低Trig脚电平
                SerialPortPublic.controlQrcodeTrigStatus(0, -1);
                return null;
            } finally {
                triggerQrcodeFuture = null;
            }
        });
    }
}
